var express		= require('express');
var app = require('express')(),
	server = require('http').createServer(app);
var fs			= require("fs");
var bodyParse	= require('body-parser');
var path		= require('path');
var url			= require("url");
var querystring	= require("querystring");
var tiMsg = require('./routes/TiMsg');

// http://192.168.1.116:3000/?selfid=1234567

var WebSocketServer = require('ws').Server,
    wss = new WebSocketServer({port: 8080});
// 连接池
var clients = {};

wss.on('connection', function(ws) {
	// 收到连接信息
    ws.on('message', function(message) {
		message = JSON.parse(message);
		if (message.type === "REGISTER") {
			clients[message.selfid] = ws;
			console.log(message.selfid,'拿到什么');
		}
    });

    // ws.on('close', function(message) {
    //     // 连接关闭时，将其移出连接池
    //     clients = clients.filter(function(ws1){
    //         return ws1 !== ws
    //     })
    // });
});

app.use(bodyParse.urlencoded({extended:false}));
// 通过这句话，可以将一个工具类的js脚本放到public文件夹中 
app.use(express.static(path.join(__dirname, 'public')));


// 处理get充值订单初始页请求
app.get('/',function(req,res){
	// 获取返回的url对象的query属性值 
	var arg = url.parse(req.url).query;
	if(arg) {
		//将arg参数字符串反序列化为一个对象
		var params = querystring.parse(arg);
		console.log("params = ",params);
		// 请求的方式
		console.log("method = " + req.method);
		// 请求的url
		console.log("url = " + req.url);
		if(!params.val) {
			// 设置上半段脚本定义的内容 包括用户id和 对应客服id
			var str = "<script>var selfid=" + params.selfid + "</script>";
			fs.readFile("./public/placeOrder.html",function(err,data){
				// body
				if(err){
					console.log(err);
					//404：NOT FOUND
					res.writeHead(404,{"Content-Type":"text/html"});
				}
				else{
					//200：OK
					res.writeHead(200,{"Content-Type":"text/html"});		// 包头
					res.write(str + data.toString());						// 结合甩出上半段脚本和下半段html页面
				}
				res.end();
			});
			console.log('用户打开充值首页+++++++++++++++++++',params.selfid);
		}else if(params.val == "applyForRefund") {
			// 设置上半段脚本定义的内容 包括用户id和 对应客服id
			var str = "<script>var selfid=" + params.selfid + "</script>";
			fs.readFile("./public/applyForRefund.html",function(err,data){
				// body
				if(err){
					console.log(err);
					//404：NOT FOUND
					res.writeHead(404,{"Content-Type":"text/html"});
				}
				else{
					//200：OK
					res.writeHead(200,{"Content-Type":"text/html"});		// 包头
					res.write(str + data.toString());						// 结合甩出上半段脚本和下半段html页面
				}
				res.end();
			});
			console.log('用户打开退款申请+++++++++++++++++++',params.selfid);
		}else if(params.val == "orderRecord") {
			// 设置上半段脚本定义的内容 包括用户id和 对应客服id
			var str = "<script>var selfid=" + params.selfid + "</script>";
			fs.readFile("./public/orderRecord.html",function(err,data){
				// body
				if(err){
					console.log(err);
					//404：NOT FOUND
					res.writeHead(404,{"Content-Type":"text/html"});
				}
				else{
					//200：OK
					res.writeHead(200,{"Content-Type":"text/html"});		// 包头
					res.write(str + data.toString());						// 结合甩出上半段脚本和下半段html页面
				}
				res.end();
			});
			console.log('用户打开订单记录+++++++++++++++++++',params.selfid);
		}
	}
});

// 向数据库发起请求 比对二级密码
app.post('/passwordCheck', async (req,res) => {
	console.log(req.body.id,req.body.password,req.body.money1,req.body.cur_Money,'password出去');
	if(req.body.money1 || req.body.cur_Money) {
		if(parseInt(req.body.money1) > parseInt(req.body.cur_Money) 
		|| req.body.cur_Money < 100) {
			res.json({"status":"fail",msg:"下单失败,输入金额大于账户余额或余额不足100"});
			console.log('下单失败,输入金额大于账户余额或余额不足100');
		}else {
			let rows = await tiMsg.matching(req.body.id);
			if(rows.length >= 1) {
				console.log(rows[0].password,'二级密码难道的是');
				if(rows[0].password == req.body.password) {
					var t1 = new Date().getTime();
					res.json({"status":"success",msg:"二级密码正确",time:t1});
					console.log(rows,t1,'二级密码正确！！！');
				}else {
					res.json({"status":"fail",msg:"二级密码错误"});
					console.log(rows,'二级密码错误');
				}
			}else {
				res.json({"status":"fail",msg:"无用户二级密码"});
				console.log(rows,'无用户二级密码');
			}
		}
	}else {
		let rows = await tiMsg.matching(req.body.id);
		if(rows.length >= 1) {
			console.log(rows[0].password,'二级密码难道的是');
			if(rows[0].password == req.body.password) {
				var t1 = new Date().getTime();
				res.json({"status":"success",msg:"二级密码正确",time:t1});
				console.log(rows,'二级密码正确？？？');
			}else {
				res.json({"status":"fail",msg:"二级密码错误"});
				console.log(rows,'二级密码错误');
			}
		}else {
			res.json({"status":"fail",msg:"无用户二级密码"});
			console.log(rows,'无用户二级密码');
		}
	}
});

// 向数据库发起请求 查询账户余额
app.post('/user_data', async (req,res) => {
	console.log(req.body.id,'userdata出去');
	let rows = await tiMsg.get_user_data(req.body.id);
	if(rows.length >= 1) {
		res.json({"status":"success",user_data:rows});
		console.log(rows,'数据回来了');
	}else {
		res.json({"status":"fail",user_data:'无数据'});
		console.log(rows,'无订单');
	}
});

// 向数据库发起请求 查询订单处理状态
app.post('/order_status', async (req,res) => {
	console.log(req.body.id,'order出去');
	let rows = await tiMsg.get_order_status(req.body.id);
	if(rows.length >= 1) {
		res.json({"status":"success",order_data:rows});
		console.log(rows,'数据回来了');
	}else {
		res.json({"status":"fail",order_data:'无订单'});
		console.log(rows,'无订单');
	}
});
server.listen(3000);
